package tgc.edu.library.web.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import tgc.edu.library.custom.DatagridUtils;
import tgc.edu.library.custom.HttpUtils;
import tgc.edu.library.custom.TimeUtils;
import tgc.edu.library.custom.WxGridParam;
import tgc.edu.library.entity.Book;
import tgc.edu.library.entity.BorrowRecord;
import tgc.edu.library.entity.Reader;
import tgc.edu.library.entity.SysUser;
import tgc.edu.library.service.BookService;
import tgc.edu.library.service.BorrowRecordService;
import tgc.edu.library.service.ReaderService;
import tgc.edu.library.service.SysUserService;

@Controller
@RequestMapping(value="/wx")
public class WeixinController {
	@Value("${wx.appid}") // spring配置文件配置了appID
	private String appId; 
    @Value("${wx.appsecret}") // spring配置文件配置了secret
    private String secret;

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private ReaderService readerService;
	@Autowired
	private BookService bookService;
	@Autowired
	private BorrowRecordService recordService;
	
	 /****
     * 微信登录
     * @param code
     * @return
     */
	@RequestMapping("/openId")
    @ResponseBody
    public Object openId(String openId){ // 小程序端获取的CODE
        Reader reader = readerService.findByOpenid(openId);
        if (reader==null) {
			return false;
		}
        
		return true;
    }
	
	/***
	 * 微信绑定账号
	 * @param username
	 * @param password
	 * @param code
	 * @return
	 */
	@RequestMapping(value="/register")
	@ResponseBody
	public Map<String, Object> register(String username, String password , String openId){ // 小程序端获取的CODE
		Map<String, Object> result = new HashMap<>();
		System.err.println(username+"++++"+password);
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		SysUser user = sysUserService.findByUsername(username);
		if(user==null) {
			result.put("code", 1);
			result.put("msg", "绑定失败");
		}else {
			boolean f = encoder.matches(password,user.getPassword());
			if(f) {
				user.setOpenid(openId);
				sysUserService.save(user);
				result.put("code", 0);
				result.put("msg", "绑定成功");
			}else {
					result.put("code", 2);
					result.put("msg", "绑定失败");
				}
			}
		return result;
	}


	/***
	 * 个人信息
	 * @param code
	 * @return
	 */
	@RequestMapping("/reader")
    @ResponseBody
    public Map<String, Object> grxx(String openId){ // 小程序端获取的CODE
        Map<String, Object> result = new HashMap<>();
            Reader user = readerService.findByOpenid(openId);
            if(user==null) {
            	result.put("code", 1);
            	result.put("msg", "你还未绑定账号！");
            }else {
            	result.put("code", 0);
            	result.put("msg", "登录成功");
            	result.put("data", user);
            }
		return result;
    }
	
	/**
	 * 
	 * 所有图书
	 * @return
	 * 
	 * */
	@RequestMapping(value="/bookall")
	@ResponseBody
	public Object page(WxGridParam param) throws InterruptedException{
		Sort sort = Sort.by(Sort.Direction.DESC,"id");
		Pageable pageable = param.getPageable(sort);
		Page<Book> page = bookService.findAll(pageable);
		return DatagridUtils.biuldDatagridResult(page);
	}
	
	/**
	 * 
	 * 借书记录
	 * @param code
	 * @return
	 * 
	 * */
	@RequestMapping(value="/recordall")
	@ResponseBody
	public Object recordall(WxGridParam param,String openId) throws InterruptedException{
		Reader user = readerService.findByOpenid(openId);
		Sort sort = Sort.by(Sort.Direction.DESC,"id");
		Pageable pageable = param.getPageable(sort);
		Page<BorrowRecord> page = recordService.findByReaderAndStatus(user,"已同意",pageable);
		return DatagridUtils.biuldDatagridResult(page);
	}
	
	/**
	 * 
	 * 申请借阅图书
	 * @param bookCode
	 * @param code
	 * @return
	 * 
	 * */
	@RequestMapping(value="recordsave")
	@ResponseBody
	public Object recordsave(Integer bookid,String openId) {
			Book book = bookService.findById(bookid);
			Reader reader = readerService.findByOpenid(openId);
			BorrowRecord record = recordService.findByReaderAndBook(reader, book);
			BorrowRecord record1 = new BorrowRecord();
			String stringDate = TimeUtils.getStringDate();
			record1.setBook(book);
			record1.setApplytime(stringDate);
			record1.setStatus("申请中");
			record1.setReader(reader);
			recordService.save(record1);
			return true;
	}
	
	/**
	 * 
	 * 还书
	 * @param bookCode
	 * @param code
	 * @return
	 * 
	 * */
	@RequestMapping(value="/borrowsave")
	@ResponseBody
	public Object borrowsave(Integer recordid,Integer bookid) {
		String stringDate = TimeUtils.getStringDate();
		BorrowRecord record = recordService.findById(recordid);
		Book book = bookService.findById(bookid);
		Integer quantity = book.getQuantity()+1;
		book.setQuantity(quantity);
		record.setGivetime(stringDate);
		record.setStatus("已归还");
		bookService.save(book);
		recordService.save(record);
		return true;
	}
}
